package com.supermate.supercut.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.supermate.init.dto.MultiResult;
import com.supermate.init.dto.Result;
import com.supermate.init.exceptions.BusinessException;
import com.supermate.init.exceptions.SystemException;
import com.supermate.init.util.LogUtil;
import com.supermate.supercut.app.constant.AppConstant;
import com.supermate.supercut.app.request.SaveTextRequest;
import com.supermate.supercut.app.request.UploadFileRequest;
import com.supermate.supercut.app.service.ClipBoardWriteService;
import com.supermate.init.exceptions.BusinessException;
import com.supermate.init.exceptions.SystemException;
import com.supermate.init.util.LogUtil;
import com.supermate.supercut.app.enums.ErrorEnums;
import com.supermate.supercut.app.enums.ExceptionsGetter;
import com.supermate.supercut.app.service.ClipboardReadService;
import com.supermate.supercut.app.vo.ResourceVo;
import com.supermate.supercut.domain.model.ClipboardText;
import com.supermate.supercut.domain.model.FileResource;
import com.supermate.supercut.domain.repo.ClipboardResourceRepo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Objects;

/**
 * @author jiao.zhou
 */
@RestController
@RequestMapping("/clipboard")
public class ClipboardController {

    @Autowired
    ClipBoardWriteService clipBoardWriteService;
    @Autowired
    private ClipboardReadService clipboardReadService;

    @GetMapping("/hello")
    public Result<String> hello() {
        System.out.println("hello clipboard!");
        return Result.success("hello clipboard!");
    }

    @GetMapping("/queryDetails")
    public Result<ResourceVo> queryDetails(@RequestParam("clipboardName") String clipboardName) {
        try {
            if (StringUtils.isBlank(clipboardName)) {
                throw ExceptionsGetter.getBizException(ErrorEnums.CLIPBOARD_NAME_EXPECT_NOT_BLANK);
            }
            ResourceVo clipboardResources = clipboardReadService.getClipboardResources(clipboardName);
            return Result.success(clipboardResources);
        } catch (BusinessException | SystemException e) {
            LogUtil.error("ClipboardController#queryDetails",new Object[]{clipboardName}, e);
            return Result.fail(e.getErrorCode(), e.getErrorMsg());
        } catch (Throwable t) {
            LogUtil.error("ClipboardController#queryDetails",new Object[]{clipboardName}, t);
            return Result.fail(ErrorEnums.UNKNOWN_ERROR.getErrCode(), ErrorEnums.UNKNOWN_ERROR.getErrMsg());
        }

    }

    @PostMapping("/saveText")
    public Result<Boolean> saveText(@RequestBody SaveTextRequest request){
        try {
            String clipBoardName = request.getClipboardName();
            String clipBoardText = request.getClipboardText();
            if(StringUtils.isBlank(clipBoardName)) {
                throw ExceptionsGetter.getBizException(ErrorEnums.CLIPBOARD_NAME_EXPECT_NOT_BLANK);
            }
            Boolean saveResult = clipBoardWriteService.saveText(clipBoardName, clipBoardText);
            return Result.success(saveResult);
        }catch (BusinessException | SystemException e) {
            LogUtil.error("ClipboardController#saveText", new Object[]{request}, e);
            return Result.fail(e.getErrorCode(), e.getErrorMsg());
        }catch (Throwable t) {
            LogUtil.error("ClipboardController#saveText", new Object[]{request}, t);
            return Result.fail(ErrorEnums.UNKNOWN_ERROR.getErrCode(), ErrorEnums.UNKNOWN_ERROR.getErrMsg());
        }
    }


    @GetMapping("/downloadFile")
    public ResponseEntity<Resource> downloadFile(@RequestParam("clipboardName") String clipboardName,
                                                 @RequestParam("fileId") String fileId) throws IOException {
        FileResource fileResource = clipboardReadService.getFileResourceByClipNameAndId(clipboardName, fileId);
        File file = new File(AppConstant.getFileAbsolutePath(fileResource.getRelativePath()).toString());
        InputStreamResource inputStreamResource = new InputStreamResource(Files.newInputStream(file.toPath()));
        // 设置响应头，告诉浏览器以附件形式下载文件
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=" + fileResource.getFileName());
        // 返回文件数据作为ResponseEntity
        return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(inputStreamResource);
    }

    @PostMapping("/uploadFile")
    @CrossOrigin(origins = "*")
    public Result<Boolean> uploadFile(UploadFileRequest request) {
        try {
            if (StringUtils.isBlank(request.getClipboardName()) || Objects.isNull(request.getMultipartFile())) {
                throw ExceptionsGetter.getBizException(ErrorEnums.CLIPBOARD_AND_FILE_EXPECT_NOT_NULL);
            }
            clipBoardWriteService.saveFile(request.getClipboardName(), request.getMultipartFile());
            return Result.success(true);
        } catch (BusinessException | SystemException e) {
            //LogUtil.error("ClipboardController#uploadFile", new Object[]{request}, e);
            return Result.fail(e.getErrorCode(), e.getErrorMsg());
        } catch (Throwable t) {
            //LogUtil.error("ClipboardController#uploadFile", new Object[]{request}, t);
            return Result.fail(ErrorEnums.UNKNOWN_ERROR.getErrCode(), ErrorEnums.UNKNOWN_ERROR.getErrMsg());
        }
    }

    //delete file
//    @DeleteMapping("/deleteFile")
//    public Result<Boolean> deleteFile(@RequestBody DeleteFileRequest request) {
//
//    }

}
